package Exam;

import java.util.Arrays;
import java.util.Iterator;

/**
 * @author げっしょく
 * @date 2021/7/25
 */
public class MyArrayList<E> implements Iterable<E> {
    private Object[] elementData= {};
    int size;
    public boolean add(E e){
        if(elementData.length == size){
            grow();
        }
        elementData[size] = e;
        size++;
        return true;
    }


    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < size; i++) {
            if(i == size - 1){
                sb.append(elementData[i]);
            }else{
                sb.append(elementData[i]).append(", ");
            }
        }
        sb.append("]");
        String s = sb.toString();
        return s;
    }
    public boolean remove(E e){
        for (int i = 0; i < elementData.length; i++) {
            if(e.equals(elementData[i])){
                for (int j = 0; j + 1 < size; j++) {
                    elementData[j] = elementData[j + 1];
                    break;
                }
                if(i == size - 1){
                    return false;
                }
            }
        }
        size-- ;
        return true;
    }
    public E set(int index, E e){
        if(index < 0 ){
            throw new IndexOutOfBoundsException("您寻找的索引"+index+"低于了集合的最低索引" + 0 );
        }else if( index >= size){
            throw new IndexOutOfBoundsException("您寻找的索引"+index+"超出了集合的最长索引" + (size - 1) );
        }
        E d = (E) elementData[index];
        elementData[index] = e;
        return d;

    }
    public E remove(int index){
        if(index < 0 ){
            throw new IndexOutOfBoundsException("您寻找的索引"+index+"低于了集合的最低索引" + 0 );
        }else if( index >= size){
            throw new IndexOutOfBoundsException("您寻找的索引"+index+"超出了集合的最长索引" + (size - 1) );
        }
        E e = (E) elementData[index];
        for(int i = index ;i + 1 < size ; i++){
            elementData[i] = elementData[i + 1];
        }
        size--;
        return e;
    }
    public E get(int index){
        if(index < 0 ){
            throw new IndexOutOfBoundsException("您寻找的索引"+index+"低于了集合的最低索引" + 0 );
        }else if( index >= size){
            throw new IndexOutOfBoundsException("您寻找的索引"+index+"超出了集合的最长索引" + (size - 1) );
        }
        return (E) elementData[index];
    }
    public int size(){
        return size;
    }
    private void grow() {
        int length;
        if(elementData.length == 0){
            length = 10;
        }else{
            length = elementData.length + (elementData.length >> 1);
        }
        Object[] newArray = new Object[length];
        System.arraycopy(elementData,0,newArray,0,elementData.length);
        elementData = newArray;
    }

    @Override
    public Iterator iterator() {
        return null;
    }
}
